<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="./assets/favicon.ico">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    html,
    body {
      width: 100%;
      height: 100%;
      background-color: #f5f5f5;
    }

    .container {
      height: 100%;
      display: flex;
      flex-direction: column;
    }

    .container .header {
      width: 100%;
      height: 55px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      position: fixed;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ddd;
      font-weight: 700;
      color: #666;
      z-index: 10;
    }

    .item-list {
      list-style: none;
      /* background-color: #00c8c8; */
      width: 100%;
      color: #333;
      padding: 60px 20px 20px 20px;
    }

    .item-list .item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px dashed #ccc;
      padding: 15px 0;
    }

    /* .item-list .item .create_time,
    .item-list .item .update_time {
        width: 10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    } */

    .container .footer {
      display: flex;
      justify-content: flex-end;
      padding: 20px;
    }

    .container .header>div,
    .item-list .item>div {
      flex: 1;
      display: flex;
      justify-content: center;
    }

    .operate .detail-btn,
    .operate .del-btn {
      padding: 3px 10px;
      display: flex;
      justify-content: center;
      border: none;
      outline: none;
      cursor: pointer;
      background-color: #e1e1e1;
      color: #fff;
    }

    .operate .detail-btn {
      background-color: #f56c6c;
    }

    .operate .del-btn {
      background-color: #409eff;
    }

    .mask {
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      position: fixed;
      top: 0;
      left: 0;
      z-index: 20;
      display: none;
    }

    .mask .content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 40px;
      background-color: #fff;
      display: flex;
      justify-content: center;
      flex-direction: column;
      border-radius: 10px;
    }

    .content .title {
      /* margin: 20px 0; */
      font-size: 18px;
      color: #303133;
      font-weight: 600;
    }

    .content .form {}

    .content .form .form-group {
      margin: 10px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .form-group label {
      padding: 10px 20px 10px 0;
      flex: 1;
      text-align: right;
      /* border: 1px dashed #ccc; */
      font-size: 14px;
    }

    .form-group input {
      height: 35px;
      border: none;
      outline: none;
      border-bottom: 1px dashed #ccc;
      padding: 0 60px 0 20px;
    }

    .car-plate-mock {
      border: 1px solid #fff;
      border-radius: 4px;
      background-color: #062e96;
      color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 0;
      font-weight: 700;
      letter-spacing: 2px;
      position: relative;
      margin: 0 10px;
    }

    .car-plate-mock::after {
      content: '';
      width: 96%;
      height: 87%;
      border: 1px solid #fff;
      border-radius: 4px;
      position: absolute;
      top: 2px;
      left: 2px;
    }

    .car-plate-mock .prefix::before {
      content: '';
      width: 6px;
      height: 2px;
      background-color: #fff;
      position: absolute;
      top: 5px;
      left: 40px;
      border-radius: 15px;
    }

    .car-plate-mock .prefix::after {
      content: '';
      width: 6px;
      height: 2px;
      background-color: #fff;
      position: absolute;
      bottom: 5px;
      left: 40px;
      border-radius: 15px;
    }

    .car-plate-mock .number::before {
      content: '';
      width: 6px;
      height: 2px;
      background-color: #fff;
      position: absolute;
      top: 5px;
      right: 40px;
      border-radius: 15px;
    }

    .car-plate-mock .number::after {
      content: '';
      width: 6px;
      height: 2px;
      background-color: #fff;
      position: absolute;
      bottom: 5px;
      right: 40px;
      border-radius: 15px;
    }

    .car-plate-mock .dot {
      width: 5px;
      height: 5px;
      background-color: #fff;
      border-radius: 50%;
      margin: 0 8px;
    }

    .car-plate-mock .number {}

    #numberplate_preview {
      background-color: #062e96;
      color: #fff;
    }

    .loading-wrap {
      width: 100px;
      height: 100px;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .loading-img {
      width: 50px;
      height: 50px;
      margin-bottom: 10px;
    }

    .loading-text {
      font-size: 14px;
      color: #333;
    }


    .to-top-wrap {
      position: fixed;
      bottom: 50px;
      right: 50px;
      display: none;
    }

    .to-top-btn {
      width: 60px;
      height: 60px;
      background-color: #062e96;
      color: #fff;
      border: none;
      outline: none;
      cursor: pointer;
      border-radius: 50%;
      font-size: 14px;
    }

    .search-wrap {
      width: 300px;
      height: 70px;
      /* background-color: #008c8c; */
      position: fixed;
      top: 0;
      left: -30px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-top: 1px solid #ddd;
      z-index: 20;
      cursor: pointer;
      transition: all 0.3s;

      border-top-right-radius: 10px;
      border-bottom-right-radius: 10px;
    }

    .search-wrap #search-input {
      width: 70%;
      height: 40px;
      outline: none;
      border: none;
      text-indent: 1.5em;
      border: 1px solid #ccc;
    }

    .search-wrap #serach-btn {
      width: 20%;
      height: 40px;
      background-color: #062e96;
      color: #fff;
      border: none;
      outline: none;
      cursor: pointer;
    }


  </style>
</head>

<body>

<div class="container">
  <div class="mask">
    <div class="content">
      <div class="title"></div>

      <div class="content-wrap"></div>

      <form action="" class="form">
        <div class="form-group">
          <label for="">序号</label>
          <input type="text" value="" readonly id="id">
        </div>
        <div class="form-group">
          <label for="">省份简称</label>
          <input type="text" value="" readonly id="shortname">
        </div>
        <div class="form-group">
          <label for="">车牌划分</label>
          <input type="text" value="" readonly id="letter">
        </div>
        <div class="form-group">
          <label for="">车牌名称</label>
          <input type="text" value="" readonly id="numberplate">
        </div>
        <div class="form-group">
          <label for="">车牌预览</label>
          <input type="text" value="" readonly id="numberplate_preview">
        </div>
        <div class="form-group">
          <label for="">省份编号</label>
          <input type="text" value="" readonly id="province_id">
        </div>
        <div class="form-group">
          <label for="">省份名称</label>
          <input type="text" value="" readonly id="province">
        </div>
        <div class="form-group">
          <label for="">城市编号</label>
          <input type="text" value="" readonly id="city_id">
        </div>
        <div class="form-group">
          <label for="">城市名称</label>
          <input type="text" value="" readonly id="city">
        </div>
        <div class="form-group">
          <label for="">创建时间</label>
          <input type="text" value="" readonly id="create_time">
        </div>
        <div class="form-group">
          <label for="">更新时间</label>
          <input type="text" value="" readonly id="update_time">
        </div>
        <div class="form-group">
          <label for="">备注</label>
          <input type="text" value="" readonly id="remark">
        </div>
      </form>
    </div>
  </div>

  <div class="loading-wrap">
    <img src="./assets/loading.gif" class="loading-img" />
    <div class="loading-text">loading...</div>
  </div>

  <main>
    <div class="header"></div>
    <ul class="item-list">
      <!-- fetch data -->
    </ul>
    <div class="footer">共0条</div>
  </main>

  <div class="to-top-wrap">
    <button class="to-top-btn">回到<br />顶部</button>
  </div>

  <div class="search-wrap">
    <input type="text" value="" placeholder="请输入省份简称" id="search-input">
    <button id="serach-btn">搜索</button>
  </div>
</div>

<script type="text/javascript">
  (async () => {
    const getNowDateTime = () => {
      const date = new Date();

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');

      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }





    const $ = selector => document.querySelector(selector);

    const $$ = selector => document.querySelectorAll(selector);

    const doms = {
      searchInput: $('#search-input'),
      searchBtn: $('#serach-btn'),
      searchWrap: $('.search-wrap'),
      toTopWrap: $('.to-top-wrap'),
      loadingWrap: $('.loading-wrap'),
      main: $('main'),
      header: $('.header'),
      itemList: $('.item-list'),
      footer: $('.footer'),
      mask: $('.mask'),
      maskContent: {
        title: $('.title'),
        contentWrap: $('.content-wrap'),
        form: $('.form'),
        formContent: {
          id: $('#id'),
          letter: $('#letter'),
          shortname: $('#shortname'),
          numberplate: $('#numberplate'),
          numberplate_preview: $('#numberplate_preview'),
          province_id: $('#province_id'),
          province: $('#province'),
          city_id: $('#city_id'),
          city: $('#city'),
          create_time: $('#create_time'),
          update_time: $('#update_time'),
          remark: $('#remark'),
        }
      }
    }

    const carPlateData = {
      count: 0,
      items: []
    };

    const headerArr = ["序号", "省份简称", "车牌划分", "车牌名称", "车牌预览", "省份编号", "省份名称", "城市编号", "城市名称", "创建时间", "更新时间", "备注", "操作"];

    const initHeader = (array) => {
      if (!array.length) return;

      doms.header.innerHTML = array.map(item => `<div>${item}</div>`).join('');
    }



    // 随机生成车牌号
    const generateCarPlate = () => {
      const count = 5;
      const numberArr = Array(10).fill(0).map((item, index) => index);
      const wordArr = Array(26).fill(0).map((item, index) => String.fromCharCode(65 + index)).filter(word => !['I', 'O'].includes(word));
      const newArr = [...numberArr, ...wordArr];

      const _randomIndex = (array) => {
        return Math.floor(Math.random() * array.length);
      }

      // 用来存放随机生成是六位车牌号
      let tempArr = [];

      for (let i = 0; i < count; i++) {
        const index = _randomIndex(newArr);
        tempArr.push(newArr[index]);
      }

      return tempArr.join('');
    }


    const fetchData = async () => {
      const url = 'https://harding067.github.io/data/carPlate.json';

      // const url = './data/carPlate.json';

      const resp = await fetch(url, { method: 'get' });

      return await resp.json();
    }

    const initItemList = async (searchQuery = '') => {
      let { items: itemList } = await fetchData();


      // 过滤数据
      let filteredList = itemList.filter(item => item.shortname.includes(searchQuery)).map(it => ({ ...it, create_time: getNowDateTime(), update_time: getNowDateTime() }));

      // 设置数据条数
      doms.footer.innerHTML = `共${filteredList.length}条`;

      // TODO 制作简易分页
      let dataList = filteredList.sort((a, b) => a.numberplate - b.numberplate);

      // 遍历渲染itemList
      let str = '';
      dataList?.forEach((item, index) => {
        str += `<li class="item" style="background-color: ${item.numberplate.includes('A') ? '#062e9611' : 'transparent'}">
                        <div>${item.id}</div>
                        <div>${item.shortname}</div>
                        <div>${item.letter}</div>
                        <div>${item.numberplate}</div>

                        <div class="car-plate-mock">
                            <div class="prefix">${item.numberplate}</div>
                            <div class="dot"></div>
                            <div class="number">${generateCarPlate()}</div>
                        </div>

                        <div>${item.capital}</div>
                        <div>${item.province}</div>
                        <div>${item.city_id}</div>
                        <div>${item.city}</div>
                        <div class="create_time">${item.create_time === '' ? '--' : item.create_time}</div>
                        <div class="update_time">${item.update_time === '' ? '--' : item.update_time}</div>
                        <div>${item.shortname === '川' ? '✔' : '--'}</div>
                        <div class="operate">
                           <button class="detail-btn">详情<button>
                           <button class="del-btn">删除<button>
                        </div>
                      </li>`;
      })

      if (dataList.length === 0) {
        str = `<li class="item">
                        <div>暂无数据</div>
                      </li>`;
      } else {
        doms.itemList.innerHTML = str;
      }
    }

    function load() {
      doms.loadingWrap.style.display = 'block';

      doms.main.style.display = 'none';
    }

    await load();

    // 进入页面显示loading状态，过两秒再显示主要内容区域
    setTimeout(() => {
      doms.loadingWrap.style.display = 'none';
      doms.main.style.display = 'block';
    }, 2000);

    // 初始化
    await initHeader(headerArr);
    await initItemList();

    // 绑定操作事件
    doms.mask.addEventListener('click', e => {
      doms.mask.style.display = 'none';
    }, true);

    const editBtns = $$('.detail-btn');
    const { items: itemList } = await fetchData();
    for (let i = 0; i < editBtns.length; i++) {
      editBtns[i].addEventListener('click', e => {
        // console.log(editBtns[i]);
        doms.mask.style.display = 'block';
        doms.maskContent.title.innerHTML = `${itemList[i]?.province}-${itemList[i]?.city}车牌信息详情<br/><br/>`;
        // doms.maskContent.contentWrap.innerText = JSON.stringify(itemList[i]);

        if (itemList[i].shortname === '川') {
          doms.maskContent.title.style.color = '#062e96';
        } else {
          doms.maskContent.title.style.color = '#303133';
        }

        doms.maskContent.formContent.id.value = itemList[i].id || "--";
        doms.maskContent.formContent.letter.value = itemList[i].letter || "--";
        doms.maskContent.formContent.shortname.value = itemList[i].shortname || "--";
        doms.maskContent.formContent.numberplate.value = itemList[i].numberplate || "--";
        doms.maskContent.formContent.numberplate_preview.value = `${itemList[i].numberplate}·${generateCarPlate()}` || "--";
        doms.maskContent.formContent.province_id.value = itemList[i].province_id || "--";
        doms.maskContent.formContent.province.value = itemList[i].province || "--";
        doms.maskContent.formContent.city_id.value = itemList[i].city_id || "--";
        doms.maskContent.formContent.city.value = itemList[i].city || "--";
        doms.maskContent.formContent.create_time.value = itemList[i].create_time || "--";
        doms.maskContent.formContent.update_time.value = itemList[i].update_time || "--";
        doms.maskContent.formContent.remark.value = itemList[i].shortname === '川' ? '是一个山清水秀 美丽的地方' : itemList[i].remark || "--";
      })
    }

    // 绑定滚动事件，当滚动到顶部时，下拉搜索区域
    window.addEventListener('scroll', e => {
      // console.log('当前的滚动距离：', window.scrollY);

      if (window.scrollY > 500) {
        doms.toTopWrap.style.display = 'block';
      } else {
        doms.toTopWrap.style.display = 'none';
      }
    })

    // 绑定回到顶部点击事件
    doms.toTopWrap.addEventListener('click', e => {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    });

    function initSearchWrap() {
      const customLeft = doms.searchWrap.getBoundingClientRect()['width'] - 30;

      doms.searchWrap.style.left = `-${customLeft}px`;
    }

    await initSearchWrap();

    // 搜索区域绑定点击事件
    doms.searchWrap.addEventListener('mouseenter', e => {

      doms.searchWrap.style.left = '0';
    })

    doms.searchWrap.addEventListener('mouseleave', e => {

      initSearchWrap();
    })

    // 搜索按钮绑定点击事件
    doms.searchBtn.addEventListener('click', async e => {
      const searchValue = doms.searchInput.value.trim();

      if (searchValue === '') {
        alert('请输入省份简称');
        return;
      } else {
        // 调用方法，传入搜索关键字，重新渲染列表
        await initItemList(searchValue);

        doms.searchInput.value = '';
      }
    });











    /*
    function getPlate(total = 5) {
        let stateList = '京津冀晋辽吉沪苏浙皖闽琼赣鲁豫鄂湘粤渝川贵云陕甘蒙黑桂藏青宁新'
        let charList = 'ABCDEFGHJKLMNQPRSTUVWXYZ'
        let numList = '1234567890'
        let halfList = [charList, numList]
        let state = dicingChar(stateList)
        let city = dicingChar(charList)
        let sequence = ''
        while (total--) {
            sequence += dicingChar(halfList[Math.round(Math.random())])
        }
        console.log(`${state}${city} ${sequence}`)
    }

    function dicingChar(series) {
        return series[~~(Math.random() * series.length)]
    }

    console.log(getPlate());
    */

  })();
</script>

</body>

</html>